// 菜单数据加载服务
import { getRouters } from '@/api/menu';
import { getMicroAppByPath } from '@/config/microAppConfig';

/**
 * 菜单项接口
 */
export interface MenuItem {
  path: string;
  name?: string;
  component?: string;
  redirect?: string;
  servicePrefix?: string; // 微前端服务前缀
  meta?: {
    title?: string;
    icon?: string;
    hidden?: boolean;
    isHide?: boolean;
    keepAlive?: boolean;
    isKeepAlive?: boolean;
    affix?: boolean;
    isAffix?: boolean;
    breadcrumb?: boolean;
    activeMenu?: string;
    permissions?: string[];
    isLink?: string;
    isFull?: boolean;
    [key: string]: any;
  };
  children?: MenuItem[];
}

/**
 * 加载菜单数据
 */
export const loadMenuData = async (): Promise<MenuItem[]> => {
  try {
    console.log('[MenuService] 开始加载菜单数据...');
    const response = await getRouters();
    console.log('[MenuService] API 响应:', response);

    if (response.code === 200 && response.data) {
      const menuData = response.data;
      console.log('[MenuService] 原始菜单数据:', menuData);

      // 递归转换，完整保留任意深度 children 与常用 meta 字段
      const transformMenuItem = (item: any): MenuItem => {
        const meta = item.meta || {};
        
        // 使用配置文件自动确定微前端服务前缀
        // 优先使用 component 字段判断，其次使用 path
        const microApp = getMicroAppByPath(item.path, item.component);
        
        // 🔧 调试日志：查看所有菜单项的处理过程
        if (item.component && (item.component.includes('tenant') || item.path.includes('tenant'))) {
          console.log('🔍 [MenuService] Tenant 相关菜单项处理:', {
            path: item.path,
            component: item.component,
            name: item.name,
            meta: item.meta,
            matchedApp: microApp?.name || 'none',
            microAppConfig: microApp,
            servicePrefix: microApp?.name || ''
          });
        }
        
        const node: MenuItem = {
          path: item.path,
          name: item.name || meta.title || item.path.split('/').pop() || 'Unknown',
          component: item.component,
          redirect: item.redirect,
          servicePrefix: microApp?.name || '', // 自动设置服务前缀
          meta: {
            title: meta.title || item.name || item.path.split('/').pop() || 'Unknown',
            icon: meta.icon,
            hidden: meta.hidden || meta.isHide || false,
            isHide: meta.isHide || meta.hidden || false,
            keepAlive: meta.keepAlive || meta.isKeepAlive || false,
            isKeepAlive: meta.isKeepAlive || meta.keepAlive || false,
            affix: meta.affix || meta.isAffix || false,
            isAffix: meta.isAffix || meta.affix || false,
            breadcrumb: meta.breadcrumb !== false,
            activeMenu: meta.activeMenu,
            permissions: meta.permissions || [],
            isLink: meta.isLink || '',
            isFull: meta.isFull || false,
            // 保留其他所有字段
            ...meta,
          },
        };
        
        if (Array.isArray(item.children) && item.children.length) {
          node.children = item.children.map((child: any) => transformMenuItem(child));
        }
        
        return node;
      };

      const transformedMenus = Array.isArray(menuData) 
        ? menuData.map((it: any) => transformMenuItem(it)) 
        : [];
      
      console.log('[MenuService] 转换后的菜单数据:', transformedMenus);
      return transformedMenus;
    }
    
    console.warn('[MenuService] 菜单数据获取失败，返回空数组');
    return [];
  } catch (error) {
    console.error('[MenuService] 加载菜单失败:', error);
    // 出错时返回空数组，而不是默认菜单
    return [];
  }
};

/**
 * 过滤隐藏的菜单项
 */
export const filterHiddenMenus = (menus: MenuItem[]): MenuItem[] => {
  return menus
    .filter(menu => !menu.meta?.hidden && !menu.meta?.isHide)
    .map(menu => {
      if (menu.children && menu.children.length > 0) {
        return {
          ...menu,
          children: filterHiddenMenus(menu.children)
        };
      }
      return menu;
    });
};

/**
 * 排除租户独立菜单
 * 规则：
 * - 通过微应用配置识别租户相关应用
 * - meta.tenantOnly === true 的菜单不显示
 * - 路径包含 '/tenant' 的菜单不显示
 * - component 包含 'tenant' 的菜单不显示
 */
export const excludeTenantMenus = (menus: MenuItem[]): MenuItem[] => {
  const filterFn = (list: MenuItem[]): MenuItem[] => {
    return list
      .filter(item => {
        // 多种方式判断是否为租户菜单
        const isTenantMenu = 
          item.meta?.tenantOnly === true ||
          item.path.includes('/tenant') ||
          (item.component && item.component.includes('tenant')) ||
          (item.servicePrefix && item.servicePrefix.includes('tenant'));
          
        if (isTenantMenu) {
          console.log('[MenuService] 排除租户菜单:', {
            path: item.path,
            component: item.component,
            servicePrefix: item.servicePrefix,
            tenantOnly: item.meta?.tenantOnly,
            reason: item.meta?.tenantOnly === true ? 'tenantOnly' :
                   item.path.includes('/tenant') ? 'path' : 
                   item.component && item.component.includes('tenant') ? 'component' : 'servicePrefix'
          });
        }
        return !isTenantMenu;
      })
      .map(item => {
        if (item.children && item.children.length > 0) {
          const children = filterFn(item.children);
          return { ...item, children };
        }
        return item;
      });
  };
  return filterFn(menus);
};

